package com.printhelper.service;

import com.printhelper.model.Conversion;
import com.printhelper.repository.ConversionRepository;
import com.aspose.pdf.Document;
import com.aspose.pdf.SaveFormat;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.xslf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.UUID;

@Service
public class PdfToPptService {
    
    @Autowired
    private ConversionRepository conversionRepository;
    
    @Value("${file.upload-dir}")
    private String uploadDir;
    
    @Value("${file.temp-dir}")
    private String tempDir;
    
    public Conversion convertPdfToPpt(MultipartFile file, String userId) throws IOException {
        // Create directories if they don't exist
        createDirectories();
        
        // Generate unique file names
        String originalFileName = file.getOriginalFilename();
        String fileId = UUID.randomUUID().toString();
        String pdfFileName = fileId + ".pdf";
        String pptFileName = fileId + ".pptx";
        
        // Save PDF file
        Path pdfPath = Paths.get(uploadDir, pdfFileName);
        Files.copy(file.getInputStream(), pdfPath);
        
        // Create conversion record
        Conversion conversion = new Conversion();
        conversion.setId(fileId);
        conversion.setUserId(userId);
        conversion.setOriginalFileName(originalFileName);
        conversion.setPdfFilePath(pdfPath.toString());
        conversion.setStatus("PENDING");
        conversion.setCreatedAt(LocalDateTime.now());
        conversion.setFileSize(file.getSize());
        
        conversion = conversionRepository.save(conversion);
        
        // Start conversion process
        try {
            conversion.setStatus("PROCESSING");
            conversionRepository.save(conversion);
            
            // Convert PDF to PPT
            String pptPath = convertPdfToPptInternal(pdfPath.toString(), fileId);
            
            conversion.setPptFilePath(pptPath);
            conversion.setStatus("COMPLETED");
            conversion.setCompletedAt(LocalDateTime.now());
            
        } catch (Exception e) {
            conversion.setStatus("FAILED");
            conversion.setErrorMessage(e.getMessage());
        }
        
        return conversionRepository.save(conversion);
    }
    
    private String convertPdfToPptInternal(String pdfPath, String fileId) throws IOException {
        String pptPath = Paths.get(uploadDir, fileId + ".pptx").toString();
        try {
            // 使用Aspose.PDF实现高质量PDF转PPTX
            Document pdfDocument = new Document(pdfPath);
            pdfDocument.save(pptPath, SaveFormat.Pptx);

            // ====== 新增：用POI去除Aspose水印文本框 ======
            String watermarkText = "Evaluation Only. Created with Aspose.PDF. Copyright 2001-2025 Aspose Pty Ltd.";
            try (java.io.FileInputStream fis = new java.io.FileInputStream(pptPath);
                 org.apache.poi.xslf.usermodel.XMLSlideShow ppt = new org.apache.poi.xslf.usermodel.XMLSlideShow(fis)) {
                for (org.apache.poi.xslf.usermodel.XSLFSlide slide : ppt.getSlides()) {
                    for (int i = slide.getShapes().size() - 1; i >= 0; i--) {
                        org.apache.poi.xslf.usermodel.XSLFShape shape = slide.getShapes().get(i);
                        if (shape instanceof org.apache.poi.xslf.usermodel.XSLFTextShape) {
                            String text = ((org.apache.poi.xslf.usermodel.XSLFTextShape) shape).getText();
                            if (watermarkText.equals(text.trim())) {
                                slide.removeShape(shape);
                            }
                        }
                    }
                }
                // 覆盖保存
                try (java.io.FileOutputStream out = new java.io.FileOutputStream(pptPath)) {
                    ppt.write(out);
                }
            } catch (Exception e) {
                System.err.println("[警告] 用POI去除水印失败: " + e.getMessage());
            }
            // ====== 新增结束 ======

            return pptPath;
        } catch (Exception e) {
            throw new IOException("Aspose PDF转PPT失败: " + e.getMessage(), e);
        }
    }
    
    private byte[] imageToByteArray(BufferedImage image) throws IOException {
        java.io.ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream();
        ImageIO.write(image, "PNG", baos);
        return baos.toByteArray();
    }
    
    private void createDirectories() throws IOException {
        Files.createDirectories(Paths.get(uploadDir));
        Files.createDirectories(Paths.get(tempDir));
    }
    
    public Conversion getConversion(String conversionId) {
        return conversionRepository.findById(conversionId).orElse(null);
    }
    
    public java.util.List<Conversion> getUserConversions(String userId) {
        return conversionRepository.findByUserIdOrderByCreatedAtDesc(userId);
    }
} 